<template>
<div>
  <div class="divTop" v-model="search">
    <span>小区名称</span><el-input v-model="search.communityName" style="width: 250px" placeholder="请输入小区名称"></el-input>
    <span>小区编码</span><el-input v-model="search.communityCode" style="width: 250px" placeholder="请输入小区编码"></el-input>
      <el-button  class="souSuoBut" @click="searchDJ" type="success" size="small" icon="el-icon-search">搜索</el-button>
      <el-button @click="searchCZ" size="small" icon="el-icon-refresh">重置</el-button>
  </div>
  <!--  中层按钮-->
  <div>
    <el-row class="but-add">
      <el-button type="primary" size="small" @click="doSave('community')">添加</el-button>
      <el-button type="success" size="small" disabled>修改</el-button>
      <el-button type="danger" size="small" @click="deleteRoles" :disabled="isDisabled">批量删除</el-button>
      <el-button type="warning" size="small" @click="derive">导出</el-button>
    </el-row>
  </div>
  <!--  数据展示-->
  <el-table
      :data="communitys"

      :cell-style="{'text-align':'center'}"
      :header-cell-style="{background:'#F8F8F9','text-align':'center',color:'#000'}"
      @select="selectCommunityOneId"
      @select-all="selectCommunityAllIds"
      style="width: 100%">
    <el-table-column type="selection"></el-table-column>
    <el-table-column
        type="index"
        label="序号"
        width="100">
    </el-table-column>
    <el-table-column
        prop="communityName"
        label="小区名称"
        width="180">
    </el-table-column>
    <el-table-column
        prop="communityCode"
        label="小区编码"
        width="180">
    </el-table-column>
    <el-table-column
        prop="dartName"
        label="省"
        width="150">
    </el-table-column>
    <el-table-column
        prop="cityName"
        label="市"
        width="150">
    </el-table-column>
    <el-table-column
        prop="countyName"
        label="区/县"
        width="150">
    </el-table-column>
    <el-table-column
        prop="createTime"
        label="创建时间"
        width="200">
    </el-table-column>
    <el-table-column
        prop="remark"
        label="备注"
        width="150">
    </el-table-column>
    <el-table-column
        label="操作">
      <template slot-scope="scope">
        <el-button @click="doEdit(scope.row)" type="text" size="small">修改</el-button>
        <el-button @click="deleteCommunity(scope.row.communityId)" type="text" size="small">删除</el-button>
        <el-button @click="doTenement(scope.row)" type="text" size="small">更换物业</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--  分页-->
  <div class="block">
    <el-pagination
        @size-change="sizeTo"
        @current-change="pageTo"
        :current-page="page"
        :page-sizes="[1,3,20, 30, 40]"
        :page-size="3"
        layout="total, sizes, prev, pager, next, jumper"
        :total="sizes">
    </el-pagination>
  </div>
  <!--  添加或修改弹窗-->
  <el-dialog title="数据权限" width="500px" :visible.sync="community_window">
    <el-form :model="community" :rules="rules" ref="community" label-width="100px" class="demo-ruleForm">
      <el-form-item label="小区名称" prop="communityName">
        <el-input v-model="community.communityName"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="communityDetailedAddress">
        <el-input v-model="community.communityDetailedAddress" ></el-input>
      </el-form-item>
      <el-form-item label="所属区划">
        <el-cascader
            v-model="areaCodeIds"
            :options="areaTrees"
            :props="areaTree"
            @change="areaCodeClick"></el-cascader>
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="community.remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="(save('community'))">确认</el-button>
        <el-button @click="community_window=false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--  更改物业弹窗-->
  <el-dialog title="更换物业" width="700px" :visible.sync="tenement_window">
    <el-table
        :data="depts"
        style="width: 100%"
        row-key="deptId"
        default-expand-all
        :tree-props="{children: 'childDept', hasChildren: 'hasChildren'}">
      <el-table-column
          prop="deptName"
          label="部门名称">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态">
        <template slot-scope="scop">
          <span v-if="scop.row.status == '0'">正常</span>
          <span v-if="scop.row.status == '1'">停用</span>
        </template>
      </el-table-column>
      <el-table-column
          header-align="center"
          align="center"
          prop="createTime"
          label="创建时间">
      </el-table-column>
      <el-table-column
          header-align="center"
          align="center"
          label="操作">
        <template slot-scope="scope" v-if="scope.row.parentId==100">
          <el-button v-if="deptId == 0 " @click="tenementAdd(scope.row)" type="text" size="small">选择</el-button>
          <el-button v-if="deptId != 0 && deptId==scope.row.deptId" type="text" size="small">已选择</el-button>
          <el-button v-if="deptId != 0 && deptId!=scope.row.deptId" @click="tenementAdd(scope.row)" type="text" size="small">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</div>
</template>

<script>
import {saveAs} from "file-saver";
export default{
  name:"RoleView",
  data(){
    return{
      communitys:[],
      pages:1,
      page:1,
      size:3,
      sizes:0,
      communityIds:[],
      //搜索实体
      search:{communityName:null,communityCode:null},
      isDisabled:true,
      community_window:false,
      community:{"communityId":null,"communityName":"","communityCode":"","communityProvenceCode":"","communityCityCode":"","communityTownCode":"","communityDetailedAddress":"","communityLongitude":null,"communityLatitude":null,"deptId":null,"communitySort":null,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null},
      rules:{
        communityName:[{required: true, message: '小区名称不能为空', trigger: 'blur' }],
        communityDetailedAddress:[{required: true, message: '详细地址不能为空', trigger: 'blur' }],
      },
      areaTrees:[],
      areaTree:{
          label:"name",
          value:"code",
          children:"childArea",
      },
      areaCodeIds:[], //省市区划码数组
      //物业
      tenement_window:false,
      depts:[],
      //更换物业容器
      deptId:"",
      communityId:""
    }
  },
  methods:{
    selectAllCommunity(page,size){
      this.page=page;
      this.size=size;
      this.$axios.post("/zyCommunity/selectAllZyCommunity/"+page,{
        size:this.size,
        communityName:this.search.communityName,
        communityCode:this.search.communityCode,
      }).then(result =>{
        if (result.data.code==200){
          this.communitys = result.data.data.records;
          this.pages = result.data.data.pages;
          this.sizes = result.data.data.total;
        }
      })
    },
    //页码刷新
    pageTo(val){
      this.selectAllCommunity(val,this.size);
      this.page=val;
    },
    //条数刷新
    sizeTo(val){
      this.selectAllCommunity(this.page,val);
      this.size=val;
    },
    //获取多行数据
    selectCommunityOneId(val){
      this.communityIds=[];
      for (let i = 0; i < val.length; i++) {
        this.communityIds[i]=val[i].communityId;
      }
      console.log(this.communityIds)
      this.deletesBut();
    },
    //获取全部行数据
    selectCommunityAllIds(val){
      this.communityIds=[];
      for (let i = 0; i < val.length; i++) {
        this.communityIds[i]=val[i].communityId;
      }
      console.log(this.communityIds)
      this.deletesBut();
    },
    //搜索重置点击
    searchCZ(){
      this.search={communityName:null,communityCode:null};
      this.selectAllCommunity(this.page,this.size);
    },
    //搜索点击
    searchDJ(){
      this.selectAllCommunity(1,this.size);
    },
    //判断批量删除按钮
    deletesBut(){
      if (this.communityIds.length>1){
        this.isDisabled = false;
      }else {
        this.isDisabled = true;
      }
    },
    //添加之前的初始化操作
    doSave(community){
      this.community={"communityId":null,"communityName":"","communityCode":"","communityProvenceCode":"","communityCityCode":"","communityTownCode":"","communityDetailedAddress":"","communityLongitude":null,"communityLatitude":null,"deptId":null,"communitySort":null,"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null};
      this.selectAreaTree();
      this.areaCodeIds=[];
      this.community_window = true;
      this.$refs[community].resetFields();
    },
    //查询地址树
    selectAreaTree(){
      this.areaTrees=[];
      this.$axios.get("/sysArea/selectAreaAllTree")
          .then(result =>{
            if (result.data.code==200){
              this.areaTrees=result.data.data;
            }
          })
    },
    //级联选择器点击事件
    areaCodeClick(){
      this.community.communityProvenceCode = this.areaCodeIds[0];
      this.community.communityCityCode = this.areaCodeIds[1];
      this.community.communityTownCode = this.areaCodeIds[2];
    },
    //修改前的初始化操作
    doEdit(community){
      this.areaCodeIds=[parseInt(community.communityProvenceCode),parseInt(community.communityCityCode),parseInt(community.communityTownCode)];
      this.community = JSON.parse(JSON.stringify(community));
      console.log(this.community)
      this.selectAreaTree();
      this.community_window = true;
    },
    save(community){
      if (this.community.communityId == null){
        this.$refs[community].validate((valid) => {
          if (valid) {
            // localStorage.getItem("userName") //传入登录用户名，也就是创建角色用户
            this.community.createBy=localStorage.getItem("username");//测试给默认值后续删
            this.$axios.post("/zyCommunity/communityAdd",this.community)
                .then(result =>{
                  if (result.data.code==200){
                    this.community_window = false;
                    this.selectAllCommunity(this.page,this.size);
                    this.$message({
                      message: '恭喜你，'+result.data.data,
                      type: 'success'
                    });
                  }else {
                    this.$message({
                      message: '警告哦，'+result.data.message,
                      type: 'warning'
                    });
                  }
                })
          } else {
            console.log("没写完")
            return false;
          }
        });
      }else {
        // localStorage.getItem("userName") //传入登录用户名，也就是创建角色用户
        this.community.updateBy=localStorage.getItem("username");//测试给默认值后续删
        this.$axios.put("/zyCommunity/communityEdit",this.community)
            .then(result =>{
              if (result.data.code==200){
                this.community_window = false;
                this.selectAllCommunity(this.page,this.size);
                this.$message({
                  message: '恭喜你，'+result.data.data,
                  type: 'success'
                });
              }else {
                this.$message({
                  message: '警告哦，'+result.data.message,
                  type: 'warning'
                });
              }
            })
      }
    },
    //删除
    deleteCommunity(communityId){
      this.$confirm('是否删除该角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(()=>{
        this.$axios.delete("/zyCommunity/communityDelete/"+communityId)
            .then(result =>{
              if (result.data.code==200){
                if (this.communitys.length==1 && this.page>1){
                  this.selectAllCommunity(this.page-1,this.size);;
                }else {
                  this.selectAllCommunity(this.page,this.size);
                }
                this.$message({
                  type: 'success',
                  message: result.data.data,
                });
              }
            })
      }).catch(() => {
        this.selectAllCommunity(this.page,this.size);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //批量删除点击事件
    deleteRoles(){
      this.$confirm('此操作将删除多个小区信息，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(()=>{
        this.$axios.delete("/zyCommunity/communityDeletes?communityIds="+this.communityIds)
            .then(result =>{
              if (result.data.code==200){
                if (this.communitys.length==1 && this.page>1){
                  this.selectAllCommunity(this.page-1,this.size);
                }else {
                  this.selectAllCommunity(this.page,this.size);
                }
                this.$message({
                  type: 'success',
                  message: result.data.data,
                });
                this.isDisabled=true;
              }
            })
      }).catch(() => {
        this.selectAllCommunity(this.page,this.size);
        this.isDisabled=true;
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //导出
    derive(){
      this.$prompt('请输入导出文件名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        this.$axios.get("/zyCommunity/derive?communityIds="+this.communityIds,{responseType: 'arraybuffer'})
            .then(result =>{
              const blob = new Blob([result.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
              saveAs(blob, value + '.xlsx');
              this.selectAllCommunity(this.page,this.size);
              this.$message({
                type: 'success',
                message: '文件：'+value+'导出成功！'
              });
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消导出！'
        });
      });
    },
    //打开物业弹窗前的初始化操作
    doTenement(com){
      this.deptId ="";
      this.communityId ="";
      this.selectDeptAll();
      this.deptId =com.deptId;
      this.communityId =com.communityId;
      console.log("11111",com)
      console.log(this.deptId)
      console.log(this.communityId)
      this.tenement_window = true;
    },
    //查询部门树
    selectDeptAll(){
      this.$axios.get("/sysDept/deptTree")
          .then(result =>{
            if (result.data.code==200){
              this.depts = result.data.data;
              console.log(this.depts)
            }
          })
    },
    //更换物业
    tenementAdd(dept){
      console.log("部门",dept)
      this.$confirm('是否确定将物业部门更换为'+dept.deptName, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.put("/zyCommunity/editDeptId",{
          deptId:dept.deptId,communityId:this.communityId
        })
            .then(result =>{
              if (result.data.code==200){
                this.tenement_window = false;
                this.selectAllCommunity(this.page,this.size);
                this.$message({
                  type: 'success',
                  message: result.data.data,
                });
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    }



  },
  mounted() {
    this.selectAllCommunity(this.page,this.size);
  }
}
</script>

<style scoped>
.divTop{
  margin-bottom: 20px;
  text-align: left;
}
.divTop>span{
  margin-right: 10px;
  margin-left: 20px;
}
.block{
  float: right;
  margin-right: 30px;
  margin-top: 30px;
}
.souSuoBut{
  margin-left: 20px;
}
.but-add{
  float: left;
  margin-bottom: 20px;
}
</style>